package com.feihong.txgw.ui.fragment.nearby;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adapter.base.BaseQuickAdapter;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.nearbystore.NearByStoresReAdapter;
import com.feihong.txgw.inter.contract.mendian.IMenDainContract;
import com.feihong.txgw.tx_precenter.MenDianMainPrecenter;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.nearby.NearbyModel;

import com.feihong.txgw.ui.activity.Nearby.MenDianDetailActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompatFragment;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.UserLoginInfo;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

import static com.feihong.txgw.http.HttpTools.MENDIAN_ALL_URL;

/**
 * Created by PVer on 2017/7/3.
 * 附近门店Fragment
 */

@RuntimePermissions
public class FuJinMenDianFragment extends BaseMVPCompatFragment<IMenDainContract.AbMenDianMainPrecenter> implements
        IMenDainContract.IMenDianMainView, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.listRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    /**
     * 连接服务器失败
     */
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mReQueryDataLL;
    @BindView(R.id.fujinmendian_no_layout)
    LinearLayout mMendianNullLayout;
    @BindView(R.id.nearby_store_null_warning_msg) TextView mNullLayoutMsg;
    String Latitude, Longitude, citycode;
    private String ziti;

    private HashMap<String, String> mParams = new HashMap<>();
    private NearByStoresReAdapter mReAdapter;
    private boolean isHasData = false, isFullPage;

    private static String mWarningMsg;
    public static FuJinMenDianFragment newInstance(String tabName) {
        FuJinMenDianFragment rechargeFragment = new FuJinMenDianFragment();
        rechargeFragment.tag = tabName;
        if(tabName == MENDIAN_ALL_URL){
            mWarningMsg = "暂无门店信息";
        }else {
            mWarningMsg = "您当前位置暂无门店信息";
        }
        return rechargeFragment;
    }

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_nearby_fujinmenmian;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //绑定View
        initView();
        mNullLayoutMsg.setText(mWarningMsg);
        Latitude = UserLoginInfo.getUserCityInfo().getLatitude();
        Longitude = UserLoginInfo.getUserCityInfo().getLongitude();
        citycode = UserLoginInfo.getUserCityInfo().getCityCode();
        //绑定数据
        bindData();
    }

    @Override
    public void initView() {
        super.initView();
        Intent iit = _mActivity.getIntent();
        ziti = iit.getStringExtra("ziti");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isHasData = false;
                isFullPage = false;
                mSwipeRefreshLayout.setRefreshing(true);
                getData(true);
            }
        });
    }

    @Override
    public void bindData() {
        initAdapter();
        mConnectErrorLayout.setVisibility(View.GONE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                getData(true);
            }
        }, 200);
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {
        mReAdapter = new NearByStoresReAdapter(0);
        mReAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mReAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                NearbyModel.DataBean.ListBean item = (NearbyModel.DataBean.ListBean) adapter.getItem(position);
                startActivity(new Intent(_mActivity, MenDianDetailActivity.class)
                        .putExtra("store_id", item.getStore_id())
                        .putExtra("store_name", item.getStore_name()));
            }
        });
        mReAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_tel) {
                    NearbyModel.DataBean.ListBean item = (NearbyModel.DataBean.ListBean) adapter.getItem(position);
                    mTelNum = item.getStore_tel();
                    FuJinMenDianFragmentPermissionsDispatcher.queryPhonePremissionWithCheck(FuJinMenDianFragment.this);
                }
            }
        });

        mRecyclerView.setAdapter(mReAdapter);
    }

    private void getData(boolean isFirstLoad) {
        mConnectErrorLayout.setVisibility(View.GONE);
        mParams.put("latitude", Latitude);
        mParams.put("longitude", Longitude);
        mParams.put("citycode", citycode);
        mParams.put("type", TextUtils.isEmpty(ziti) ? "" : ziti);
        if (isFirstLoad) {
            mPrecenter.loadMenDianInfoFirs(tag, mParams);
        } else {
            mPrecenter.loadMenDianInfo(tag, mParams);
        }
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    @OnClick(R.id.re_query_data_layout)
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.re_query_data_layout:
                mSwipeRefreshLayout.setRefreshing(true);
                getData(true);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FuJinMenDianFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void queryPhonePremission() {

        if (!TextUtils.isEmpty(mTelNum)) {
            Intent inte1 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mTelNum));
            startActivity(inte1);
        }
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRationaleForContact(PermissionRequest request) {
        // NOTE: Show a rationale to explain why the permission is needed, e.g. with a dialog.
        // Call proceed() or cancel() on the provided PermissionRequest to continue or abort
//        showRationaleDialog("请允许获取位置信息权限", request);
        request.proceed();
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void onPermissionDenied() {
    }

    private String mTelNum;

    @Override
    public void loadInfoResult(boolean isFullPage, List<NearbyModel.DataBean.ListBean> storeDatas) {
        this.isFullPage = isFullPage;
        if (isHasData) {
            mReAdapter.addData(storeDatas);
        } else {
            isHasData = true;
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mMendianNullLayout.setVisibility(View.GONE);
            mReAdapter.setNewData(storeDatas);
        }
        mReAdapter.loadMoreComplete();
    }

    @Override
    public void loadEnd() {
        if (!isHasData) {
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mMendianNullLayout.setVisibility(View.VISIBLE);
        }
        mReAdapter.loadMoreEnd(!isFullPage);
    }

    @Override
    public void loadOtherError(String waringMsg) {
        mReAdapter.loadMoreEnd(true);
        if (!TextUtils.isEmpty(waringMsg)) {
            showSystemToast(waringMsg);
        }
    }

    @Override
    public void loadDataComplated() {
        finishRefreshing();
    }

    @Override
    public void loadDataError() {
        finishRefreshing();
        mReAdapter.loadMoreFail();
        if (!isHasData) {
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.VISIBLE);
            mMendianNullLayout.setVisibility(View.GONE);
        }
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return MenDianMainPrecenter.create();
    }

    @Override
    public void onLoadMoreRequested() {
        getData(false);
    }

    private void finishRefreshing() {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }
}

